<template>
	<view class="container">
		<view v-if="showStatus">
			<uni-list>
				<uni-list-item showExtraIcon="true" :extraIcon="{type: 'location-filled'}" title="栏舍编码"
					:rightText="consume.phouseCode" />
				<uni-list-item showExtraIcon="true" :extraIcon="{type: 'location-filled'}" title="栏舍类型"
					:rightText="pType" />
				<uni-list-item showExtraIcon="true" :extraIcon="{type: 'location-filled'}" title="存储地点"
					:rightText="position" />
				<uni-list-item showExtraIcon="true" :extraIcon="{type: 'shop-filled'}" title="饲料类型" :rightText="type" />
				<uni-list-item showExtraIcon="true" :extraIcon="{type: 'settings-filled'}" title="数量"
					:rightText="consume.materiaFeedConsumeNum+' KG'" />
				<uni-list-item showExtraIcon="true" :extraIcon="{type: 'settings-filled'}" title="负责人"
					:rightText="consume.hmyStaff.staffName" />
				<uni-list-item showExtraIcon="true" :extraIcon="{type: 'calendar-filled'}" title="消耗时间"
					:rightText="consume.materiaFeedConsumeTime" />
				<uni-list-item showExtraIcon="true" :extraIcon="{type: 'chat-filled'}" title="备注">
					<template v-slot:footer>
						<input type="textarea" v-model="consume.remark"
							style="font-size: 12px;color: #999999;text-align: right;" />
					</template>
				</uni-list-item>
			</uni-list>
			<view class="button-group">
				<button type="warn" plain="true" @click="consumeDelete" style="width: 45%;border: #E53F32 solid 1px;">删除</button>
				<button type="primary" plain="true" @click="consumeEdit" style="width: 45%;">修 改</button>
			</view>
		</view>


		<!-- 修改 -->
		<view class="example" v-if="!showStatus">
			<uni-forms ref="form" :model="consumeForm"  labelWidth="80px">
				<uni-forms-item label="栏舍编号" name="phouseCode" required>
					<uni-data-select v-model="consumeForm.phouseCode" :placeholder="consumeForm.phouseCode"
						:localdata="phouseCodeList" @change="changePhouseTypeByCode"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="栏舍类型" name="phouseType" required>
					<uni-data-select v-model="consumeForm.phouseType" :placeholder="pType" :localdata="parkType"
						disabled></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="存储地点" name="materiaFeedStorePosition" required>
					<uni-data-select v-model="consumeForm.materiaFeedStorePosition" :placeholder="position"
						:localdata="store_position" @change="changeFeedTypyByPosion"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="饲料类型" name="materiaFeedType" required>
					<uni-data-select v-if="feedTypeList.length == 0" v-model="consumeForm.materiaFeedType"
						:placeholder="type" :localdata="material_type"></uni-data-select>
					<uni-data-select v-else v-model="consumeForm.materiaFeedType" placeholder="请选择饲料类型"
						:localdata="feedTypeList"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="数量" name="materiaFeedConsumeNum" required>
					<uni-easyinput type="number" v-model="consumeForm.materiaFeedConsumeNum" placeholder="请输入数量(KG)" />
				</uni-forms-item>
				<uni-forms-item label="负责人" name="materiaFeedManager" required>
					<uni-data-select v-model="consumeForm.materiaFeedManager"
						:placeholder="consumeForm.hmyStaff.staffName" :localdata="staffNameList"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="消耗时间" name="materiaFeedConsumeTime" required>
					<uni-datetime-picker type="datetime" v-model="consumeForm.materiaFeedConsumeTime" />
				</uni-forms-item>
				<uni-forms-item label="备注">
					<uni-easyinput type="textarea" v-model="consumeForm.remark" placeholder="请输入备注" />
				</uni-forms-item>
			</uni-forms>
			<view class="edit-button-group">
				<button type="primary" @click="back" style="width: 45%;" plain="true">返 回</button>
				<button type="primary" @click="editConsume('form')" plain="true" style="width: 45%;">提 交</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getConsume,
		updateConsume,
		delConsume,
		listConsume,
		findPhouseCode,
		findAllStaffName,
		addConsume,
		findStoreFeedTypeByPosition,
		findStoreNum,
		getTypes
	} from "@/api/hmy/material";

	export default {
		data() {
			return {
				showStatus: true,
				consumeId: '',
				consume: {
					hmyStaff: {
						staffName: ''
					}
				},
				consumeForm: {},
				//饲料类型
				type: '',
				typesList: [],
				position: '', //仓库位置
				pType: '', //栏舍类型
				material_type: [],
				store_position: [{
						text: '一号仓库',
						value: 1
					},
					{
						text: '二号仓库',
						value: 2
					},
					{
						text: '三号仓库',
						value: 3
					}
				],
				park_type: [{
						text: '公猪舍',
						value: 1
					},
					{
						text: '母猪舍',
						value: 2
					},
					{
						text: '肉猪舍',
						value: 3
					}
				],
				rules: {
					phouseCode: {
						rules: [{
							required: true,
							errorMessage: '栏舍编码不能为空'
						}]
					},
					materiaFeedConsumeNum: {
						rules: [{
								required: true,
								errorMessage: '消耗数量不能为空'
							},
							{
								validateFunction: async (rule, value, data, callback) => {
									//console.log('value', value)
									var positon = this.consumeForm.materiaFeedStorePosition;
									var type = this.consumeForm.materiaFeedType;
									var flag = false;
									this.feedTypeList.forEach(item => {
										if (isNaN(type)) {
											if (type == item.label) {
												flag = true;
											}
										} else {
											if (type == item.value) {
												flag = true;
											}
										}

									})
									this.typesList.forEach(item => {
										
										if(type == item.materiaFeedTypeId){
											if (!flag) {
												callback("当前仓库没有该" + item.materiaFeedType)
											}
										}
									})
									var typeName = '';
									if (positon != undefined && type != undefined) {
			
										this.typesList.forEach(item => {
											if (type == item.materiaFeedTypeId) {
												typeName = item.materiaFeedType
											}
										})
										await findStoreNum(type, positon).then(response => {
											this.nowStoreNum = response.data.materiaFeedStoreNum;
										}).catch(() => {
										})
									}
									if(this.nowStoreNum == -1){
										callback("请选择饲料类型")
										return;
									}
									if (this.nowStoreNum < value) {
										callback("不可超过现有库存（" + this.nowStoreNum + "）")
									}
								}
							}
						]
					},
					materiaFeedStorePosition: {
						rules: [{
							required: true,
							errorMessage: '存储地点不能为空'
						}]
					},
					materiaFeedType: {
						rules: [{
								required: true,
								errorMessage: '饲料类型不能为空'
							},
						]
					},
					materiaFeedManager: {
						rules: [{
							required: true,
							errorMessage: '负责人不能为空'
						}]
					},
					materiaFeedConsumeTime: {
						rules: [{
							required: true,
							errorMessage: '消耗时间不能为空'
						}]
					}
				},
				//所有的栏舍编码
				phouseCodeList: [],
				//栏舍类型
				parkType: [],
				//所有物料负责人
				staffNameList: [],
				//仓库下的饲料类型
				feedTypeList: [],
				//现有存储数量
				nowStoreNum: -1
			}
		},
		// onReady() {
		// 	// 需要在onReady中设置规则
		// 	this.$refs.form.setRules(this.rules)
		// },
	  watch: {
		showStatus(newVal, oldVal) {
		  if(!newVal){
			  this.$nextTick(() => {
			  this.$refs.form.setRules(this.rules);
			});
		  }
			
		}
	  },

		created() {
			this.getTypesList();
			findPhouseCode().then(response => {
				var phouseList = response.data;
				phouseList.forEach(item => {
					this.phouseCodeList.push({
						'text': item.phouseCode,
						'value': item.phouseCode
					})
				})
				//console.log(this.phouseCodeList)
			});
			findAllStaffName().then(response => {
				var staffList = response.data;
				staffList.forEach(item => {
					this.staffNameList.push({
						'text': item.staffName,
						'value': item.staffId
					})
				})
				//console.log(this.staffNameList);
			})
		},
		onLoad(option) { //option为object类型，会序列化上个页面传递的参数
			//console.log(option.id);
			this.consumeId = option.id;
			this.getTypesList();
			this.getConsumeInfo();
		},
		methods: {
			//动态获取饲料数据
			getTypesList() {
				getTypes().then(res => {
					this.typesList = res.data;
					this.typesList.forEach(item => {
						this.material_type.push({
							'text': item.materiaFeedType,
							'value': item.materiaFeedTypeId
						})
					})
				})
			},
			//获取消耗记录
			getConsumeInfo() {
				//显示加载框
				uni.showLoading({
					title: "加载中"
				})
				getConsume(this.consumeId).then(response => {
					this.consumeForm = response.data;
					this.consume = response.data;
					this.typesList.forEach(typeItem => {
						if (this.consume.materiaFeedType == typeItem.materiaFeedTypeId) {
							this.type = typeItem.materiaFeedType
						}
					})

					if (this.consume.materiaFeedStorePosition == 1) {
						this.position = this.$dict.selectDictLabel('materia_feed_store_position', 1);
					} else if (this.consume.materiaFeedStorePosition == 2) {
						this.position = this.$dict.selectDictLabel('materia_feed_store_position', 2);
					} else if (this.consume.materiaFeedStorePosition == 3) {
						this.position = this.$dict.selectDictLabel('materia_feed_store_position', 3);
					}

					if (this.consume.phouseType == 1) {
						this.pType = this.$dict.selectDictLabel('hmy_park_type', 1);
					} else if (this.consume.phouseType == 2) {
						this.pType = this.$dict.selectDictLabel('hmy_park_type', 2);
					} else if (this.consume.phouseType == 3) {
						this.pType = this.$dict.selectDictLabel('hmy_park_type', 3);
					}

					//隐藏加载框
					uni.hideLoading();
				})
			},

			//删除
			consumeDelete() {
				//console.log("delete", this.consume.materiaFeedConsumeId)
				this.$modal.confirm('是否确认删除进货编号为"' + this.consume.materiaFeedConsumeId + '"的数据项？').then(() => {
					return delConsume(this.consume.materiaFeedConsumeId);
				}).then(response => {
					this.$modal.msgSuccess("删除成功");
					setTimeout(() => {
						this.$tab.navigateTo('/pages/hmy/material/consume');
					}, 1000)
				}).catch(() => {});
			},

			//修改
			consumeEdit() {
				//console.log("edit", this.consume.materiaFeedConsumeId)
				//显示加载框
				uni.showLoading({
					title: "加载中"
				})
				this.showStatus = !this.showStatus;
				//隐藏加载框
				uni.hideLoading();
			},

			//返回
			back() {
				this.showStatus = !this.showStatus
				this.getConsumeInfo();
			},

			//修改提交
			editConsume(form) {
				this.$refs[form].validate().then(res => {
					updateConsume(this.consumeForm).then(response => {
						this.$modal.msgSuccess("修改成功");
						setTimeout(() => {
							this.$tab.navigateTo('/pages/hmy/material/consume');
						}, 1000)

					})
				})
			},

			/**
			 * 根据栏舍编码改变栏舍类型
			 * @param value 当前下拉框的值
			 */
			changePhouseTypeByCode(value) {
				findPhouseCode().then(response => {
					var pList = response.data;
					pList.forEach((item, index) => {
						if (value === item.phouseCode) {
							if (item.phouseType == 1) {
								this.parkType.push({
									'text': '公猪舍',
									'value': item.phouseType
								})
								this.consumeForm.phouseType = '1';
							} else if (item.phouseType == 2) {
								this.parkType.push({
									'text': '母猪舍',
									'value': item.phouseType
								})
								this.consumeForm.phouseType = '2';
							} else if (item.phouseType == 3) {
								this.parkType.push({
									'text': '肉猪舍',
									'value': item.phouseType
								})
								this.consumeForm.phouseType = '3';
							}
						}
					})
				});
			},
			// 根据仓库地址获取该仓库下的饲料类型
			changeFeedTypyByPosion(position) {
				this.consumeForm.materiaFeedType = ''
				this.feedTypeList = [];
				findStoreFeedTypeByPosition(position).then(response => {
					var storeFeedTypeList = response.data;
					storeFeedTypeList.forEach(item => {
						this.typesList.forEach(type => {
							if (item.materiaFeedType == type.materiaFeedTypeId) {
								this.feedTypeList.push({
									'text': type.materiaFeedType,
									'value': type.materiaFeedTypeId
								})
							}
						})

					})
				})
				//console.log(this.feedTypeList);
			},

		}
	}
</script>

<style>
	page {
		background-color: #ffffff;
	}

	.button-group {
		display: flex;
		justify-content: space-around;
		width: 100%;
		position: fixed;
		bottom: 5px;

	}

	.example {
		padding: 15px;
		background-color: #fff;
	}

	.edit-button-group {
		display: flex;
		justify-content: space-around;
		width: 100%;
		position: fixed;
		bottom: 5px;
		left: 0px;
	}
</style>